import store from './store'
import http from './http'
import config from './config'
import $f from './fun'
import showModal from './showModal'
import $to from './jump'

export default function(url = '', data = {}, option = {}) {
  if (option.loading) uni.showLoading({
    title: option.loading,
    mask: true
  })
  return new Promise((resolve, reject) => {
    const header = {
      // 'token': store.state.token,
      'token': uni.getStorageSync('token'),
      // 'token': 123456,
      // 'token':'646265e7-fee6-4b43-9af8-cfb899483ae7',
    }
    // console.log("token", uni.getStorageSync('token'))
    uni.request({
      url: config[process.env.NODE_ENV] + url,
      data,
      timeout: 10000,
      header,
      method: option.method || 'POST',
      success: res => {
        if (process.env.NODE_ENV === 'development') {
          console.log(url, data, '=>', res)
        }
        if (option.loading) uni.hideLoading()
        console.log("res.data", res.data)
        if (res.data.code == 1) {
          resolve(res.data.data)
        } else if (res.data.code == 0) {
          this.$f.toast(res.data.msg)
        }
        else {
          console.log(url, data, '（err）=>', res)
          if ([401].includes(res.data.code)) {
            // store.dispatch('set', { token: '' })
            uni.removeStorageSync('token')
            // uni.login({
            //   success: async ({ code }) => {
            //     const { token } = await http('/api/user/auth', {
            //       code,
            //       type: 1
            //     })
            //     uni.setStorageSync({key: 'token',data: token})
            //     store.dispatch('set', { token })
            //     store.dispatch('getUser')
            //   }
            // })
          }
          if (![420].includes(res.data.errors)) {
            if (!option.nologin) this.$f.toast(res.data.msg || '请求错误')
          }

          // console.log(url, data, '（err）=>', res)
          reject({
            url,
            data,
            res: res.data
          })
        }
      },
      fail({
        errMsg
      }) {
        console.log(url, data, '（fail）=>', errMsg)
        if (option.loading) uni.hideLoading()
        uni.showToast({
          icon: 'none',
          duration: 2000,
          title: '网络错误，请重试'
        })
        reject({
          url,
          data,
          res: errMsg
        })
      }
    })
  })
}
